package com.wise.esexample.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wise.esexample.domain.SendRecord;
import com.wise.esexample.service.EsService;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.search.sort.SortBuilder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * sendRecord elasticsearch实现类
 */
@Service("sendRecordEsServiceImpl")
public class SendRecordEsServiceImpl implements EsService<SendRecord> {
    @Resource
    private TransportClient transportClient;

    @Override
    public void save(SendRecord entity) {
        IndexResponse response = transportClient.prepareIndex("record_alias", "sendRecord", entity.getUuid())
                .setSource(JSON.toJSONString(entity), XContentType.JSON)
                .get();
        System.out.println("The SendRecordEsServiceImpl response stature code:" + response.status().getStatus());
    }

    @Override
    public SendRecord findById(String id) {
        return null;
    }

    @Override
    public SendRecord queryByQueryBuilder(QueryBuilder queryBuilder) {
        return queryByQueryBuilder(queryBuilder, null);
    }

    @Override
    public SendRecord queryByQueryBuilder(QueryBuilder queryBuilder, SortBuilder sortBuilder) {
        SearchResponse searchResponse = null;
        try {
            SearchRequestBuilder requestBuilder = transportClient.prepareSearch("record_alias");
            requestBuilder.setQuery(queryBuilder);
            if (sortBuilder != null) {
                requestBuilder.addSort(sortBuilder);
            }
            searchResponse = requestBuilder.execute().actionGet();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (searchResponse == null) return null;
        System.out.println(JSON.toJSONString(searchResponse.getHits()));
        JSON obj = (JSON) JSON.parse(searchResponse.getHits().getAt(0).getSourceAsString());
        return JSONObject.toJavaObject(obj, SendRecord.class);
    }
}
